<template>
  <div class="main">
    <el-form ref="form" :model="formData" label-width="80px" :rules="rules">
      <el-form-item label="用户名" required prop="name">
        <el-input v-model="formData.name" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item label="密码" required prop="password" v-if="editType==='new'"> 
        <el-input v-model="formData.password" type="password" autocomplete="new-password"></el-input>
      </el-form-item>
      <el-form-item label="重复密码" required prop="rePassword" v-if="editType==='new'">
        <el-input v-model="formData.rePassword" type="password" autocomplete="new-password"></el-input>
      </el-form-item>
      
      <el-form-item label="手机号" prop="phone">
        <el-input v-model="formData.phone"></el-input>
      </el-form-item>
      <el-form-item label="邮箱" prop="email">
        <el-input v-model="formData.email"></el-input>
      </el-form-item>
      <el-form-item label="角色" prop="role" v-if="currentUser.role === 1">
        <el-select v-model="formData.role" placeholder="请选择角色">
          <el-option
            v-for="item in roleOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button @click="submit" type="primary">提交</el-button>
        <el-button @click="reset" type="primary">重置</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>
<script>
import { signup ,getUserInfoById ,updateUser, getRoleList } from '@/api/user'

export default {
  data(){
    return {
      currentUser:{},
      editType:'new',
      formData:{
        name:'',
        password:'',
        rePassword:'',
        phone:'',
        email:'',
        role:2
      },
      roleOptions:[],
      rules:{
        name:[
          {
            required: true,
            message: '用户名不能为空',
            trigger: 'blur',
          },
          {
            min: 3,
            max: 10,
            message: '用户名3-10个字符',
            trigger: 'blur',
          },
        ],
        password:[
          { validator : this.validatePass, trigger : 'blur'}
        ],
        rePassword:[
          { validator : this.validateRePass, trigger : 'blur'}
        ],
        phone:[
          { validator : this.validatePhone, trigger: 'blur' }
        ],
        email:[
          { validator : this.validateEmail, trigger: 'blur' }
        ]
      }
    }
  },
  async created(){
    let id = this.$route.query.id
    console.log('id:',id)
    if(id){
      id = decodeURIComponent(id)
      this.getInfoById(id)
      this.editType = 'edit'
    }
    // 获取角色列表
    let roleRes = await getRoleList()
    this.roleOptions = roleRes.data.map(item=>{
      return {
        value:item.id,
        label:item.label
      }
    })
    this.currentUser = this.$store.getters.currentUser
    
  },
  methods:{
    async submit(){
      let loginData = Object.assign({},this.formData)
      Reflect.deleteProperty(loginData,'rePassword')
      if(this.editType ==='edit'){
        Reflect.deleteProperty(loginData,'password')
      }
      
      this.$refs.form.validate(async (valid)=>{
        if(valid){
          // 新增
          let res = {}
          if(this.editType ==='new'){
            res = await signup(loginData)
          }else{
            res = await updateUser(loginData)
          }
          this.$message({
            type:'success',
            message:'保存成功'
          })
          this.$router.go(-1)
          this.$refs.form.resetFields()
        }
      })
    },
    async getInfoById(id){
      let res = await getUserInfoById({id})
      this.formData = res.data
      
    },
    validatePass(rule,value,callback){
      if(value === ''){
        callback(new Error('密码不能为空'))
      }else if(value.length > 30) {
        callback(new Error('密码不能超过30个字符'))
      }else if (this.formData.rePassword !== ''){
        this.$refs.form.validateField('rePassword')
      }
      callback()
    },
    validateRePass(rule,value,callback) {
      
      if(value ===''){
        callback(new Error('请再一次输入密码'))
      }else if(value !== this.formData.password){
        callback(new Error('两次密码不相同'))
      }
      callback()
    },
    validatePhone(rule,value,callback){
      if(value && !/^(0|86|17951)?(13[0-9]|15[012356789]|166|17[3678]|18[0-9]|14[57])[0-9]{8}$/.test(value)){
        callback('手机号格式不对')
      }
      callback()
    },
    validateEmail(rule,value,callback){
      if(value && !/\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/.test(value)){
        callback('邮箱格式不对')
      }
      callback()
    },

    reset(){
      this.$refs.form.resetFields()
    }
  }
}
</script>

<style lang="scss" scoped>
.main{
  padding:20px;
}
</style>

